﻿using McMaster.Extensions.CommandLineUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Batman.CommandLine.Commands
{
    public class InitTemplate : CommandLineApplicationBase
    {
        public override string Name => "init";

        public override string Description => "初始化目录结构";

        private string _TemplateDirectory => AppDomain.CurrentDomain.BaseDirectory + "/Templates/Default";

        private CommandOption _ForceCommandOption;

        public InitTemplate()
        {
            _ForceCommandOption = _CommandLineApplication.Option("-f|--force", "强制生成目录结构", CommandOptionType.SingleOrNoValue);
        }

        public override void OnExecute()
        {
            _CommandLineApplication.Out.WriteLine("为您初始化目录结构");

            var directory = Path.GetFileName(_CommandLineApplication.WorkingDirectory);
            var moduleName = Prompt.GetString($"模块名称？（{directory}）");
            if (string.IsNullOrEmpty(moduleName)) moduleName = directory;


            CopyFiles(moduleName);
        }

        public void CopyFiles(string moduleName)
        {
            CopyFiles(_TemplateDirectory, moduleName);
        }

        void CopyFiles(string directoryFullName, string moduleName)
        {
            var direcoties = Directory.GetDirectories(directoryFullName, "*", SearchOption.AllDirectories).ToList();

            direcoties.ForEach(d =>
            {
                var relativePath = d.Replace(_TemplateDirectory, string.Empty).TrimStart('/').TrimStart('\\');
                var targetPath = Path.Combine(_CommandLineApplication.WorkingDirectory, relativePath);
                if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath);
            });

            var files = Directory.GetFiles(directoryFullName);
            var theModuleName = ToModuleName(moduleName);
            _CommandLineApplication.Out.WriteLine(theModuleName);

            foreach (var file in files)
            {
                var fileName = file.Replace(_TemplateDirectory, string.Empty);
                fileName = Regex.Replace(fileName, @"{name}", moduleName);
                var dest = Path.Combine(_CommandLineApplication.WorkingDirectory, fileName.TrimStart('/').TrimStart('\\'));

                var txt = File.ReadAllText(file);
                txt = Regex.Replace(txt, @"{name}", moduleName);
                txt = Regex.Replace(txt, @"{moduleName}", theModuleName);

                var directoryName = Path.GetDirectoryName(dest);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                File.WriteAllText(dest, txt);
            }

            var directories = Directory.GetDirectories(directoryFullName);
            foreach (var directory in directories)
            {
                CopyFiles(directory, moduleName);
            }
        }

        private string ToModuleName(string moduleName)
        {
            var words = moduleName.Split('-').ToList();
            var array = new List<string>();
            foreach (var word in words)
            {
                if (word.Length > 0)
                {
                    var firstWord = word[0].ToString();
                    array.Add(firstWord.ToUpper() + word.Substring(1, word.Length - 1));
                }
            }
            return string.Join(string.Empty, array);
        }
    }
}
